package agent

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/analysisClient/rpc"
	"github.com/spf13/cast"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type StatisticLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 代理报表列表
func NewStatisticLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StatisticLogic {
	return &StatisticLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StatisticLogic) Statistic(req *types.StatisticRequest) (resp *types.StatisticPage, err error) {
	report, err := l.svcCtx.Analysis.Report(l.ctx, &rpc.AgentAnalysisRequest{
		AgentId:       req.AgentId,
		AgentType:     cast.ToInt32(req.AgentType),
		Level:         cast.ToInt32(req.Level),
		Sort:          req.Sort,
		Day:           req.DateType,
		DurationStart: req.DurationStart,
		DurationEnd:   req.DurationEnd,
	})
	if err != nil {
		logc.Error(l.ctx, err)
		return nil, err
	}
	_data := make([]*types.StatisticResponse, len(report.Data))
	// _dataMp := make(map[int64]*types.StatisticResponse, len(report.Data))
	for _i, _row := range report.Data {
		_rsp := &types.StatisticResponse{
			UserId:                  _row.UserId,
			Phone:                   _row.Phone,
			ParentId:                _row.ParentId,
			ImmediateSubordinate:    _row.ImmediateSubordinate,
			AllSubordinate:          _row.AllSubordinate,
			Agent:                   _row.Agent,
			RegisterTime:            _row.RegisterTime,
			LastOnlineTime:          _row.LastOnlineTime,
			UserBalance:             _row.UserBalance,
			Order:                   _row.Order,
			OrderFee:                _row.OrderFee,
			Award:                   _row.Award,
			Rebates:                 _row.Rebates,
			RechargeAvg:             _row.RechargeAvg,
			RechargeAmount:          _row.RechargeAmount,
			RechargeCount:           _row.RechargeCount,
			WithdrawAmount:          _row.WithdrawAmount,
			WithdrawCount:           _row.WithdrawCount,
			WithdrawAvg:             _row.WithdrawAvg,
			RedPacket:               _row.RedPacket,
			RechargeAward:           _row.RechargeAward,
			Sign:                    _row.Sign,
			AgentRedPacket:          _row.AgentRedPacket,
			RegisterAward:           _row.RegisterAward,
			AwardRecharge:           _row.AwardRecharge,
			FirstAboveRechargeAward: _row.FirstAboveRechargeAward,
			Level:                   _row.Level,
		}
		// _dataMp[_row.UserId] = _rsp
		_data[_i] = _rsp
	}
	return &types.StatisticPage{
		Total:    report.Total,
		Page:     report.Page,
		PageSize: report.PageSize,
		Data:     _data,
	}, nil
}

func compareNum[T int64 | float64 | int | float32 | int32](a, b T, _sort string) bool {
	if _sort == "desc" {
		return a > b
	}
	return a < b
}
